<template>
  <div id="helloWorld">
    <div class="out_container">
      <div v-for="(item, i) of websocketData" :key="i">
        {{ item }}
      </div>
    </div>
    <div style="width: 500px" v-if="showName">
      name:<el-input v-model="name"></el-input>
    </div>
    <div style="width: 500px" v-if="!showName">
      message:<el-input v-model="message"></el-input>
    </div>
    <div style="width: 500px" v-if="!showName">
      sendTo:<el-input v-model="sendTo"></el-input>
    </div>
    <el-button @click="send()" v-if="!showName"> fire </el-button
    ><el-button @click="connectWS()" v-if="showName">connect</el-button>
    <el-button @click="wsTest()">wsTest</el-button>
  </div>
</template>

<script>
import axios from "axios";
import test from "./AnotherOne";
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import WS from "../js/webscoket/WS";
export default {
  name: "HelloWorld",
  components: { t: test },
  data() {
    return {
      tableData: [],
      stompClient: "",
      timer: "",
      name: "",
      showName: true,
      websocketData: [],
      message: "",
      sendTo: "",
    };
  },
  methods: {
    wsTest() {
      // WS.domainHttp
      axios
        // .post("http://81.68.204.179:8080/api/permit/user/dashboard", {})
        .post(WS.domainHttp + "/api/notice/wsTest", {
          id: 1,
        })
        .then((resp) => {
          console.log(resp);

          //  this.  noticeList=resp.data.data.content
          if (resp && resp.data.code === 200) {
            // _this.menus = resp.data.result
            this.dashboardData = resp.data.data;
            console.log("ok");
          }
        });
    },
    connectWS() {
      this.initWebSocket();
    },
    init() {
      this.myHttp.getUser().then((res) => {
        console.log(res);
        let data = res.data.data;
        data.forEach((v) => {
          v.editable = false;
        });
        this.tableData = data;
      });
    },

    handleEdit(index, row) {
      console.log(index, row);
      this.tableData.forEach((v) => {
        v.editable = false;
      });
      row.editable = true;
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    handleConfirm(index, row) {
      let obj = { id: row.id, name: row.name };

      this.myHttp.updateUser(obj).then((res) => {
        console.log(res);
        if (res.data) {
          this.$message({
            message: "修改成功!",
            type: "success",
          });
          this.init();
        } else {
          this.$message.error("修改失败！");
        }
      });

      row.editable = false;
      console.log(index, row);
    },
    handleCancel(index, row) {
      row.editable = false;
      console.log(index, row);
    },
    initWebSocket() {
      this.connection();
      // let that= this;
      // // 断开重连机制,尝试发送消息,捕获异常发生时重连
      // this.timer = setInterval(() => {
      //   try {
      //     that.stompClient.send("test");
      //   } catch (err) {
      //     console.log("断线了: " + err);
      //     that.connection();
      //   }
      // }, 5000);
    },
    connection() {
      console.log("建立连接对象");
      // 建立连接对象

      // let socket = new SockJS('http://192.168.1.103:6677/end_point');
      //  let socket = new SockJS(WS.domain);
      // let socket = new SockJS(WS.domain);
        let url = WS.domainHttp + "/chat";
      // let socket = new SockJS(WS.domainHttp);
        let socket = new SockJS(url);
      this.stompClient = Stomp.over(socket); //使用STMOP子协议的WebSocket客户端
      let stompClient = this.stompClient;
      stompClient.connect({}, (frame) => {
        //连接WebSocket服务端
        this.showName = false;
        stompClient.subscribe(`/user/topic/to_user`, (response) => {
          console.log(response);
          let body = JSON.parse(response.body);
          let result = `${body.name} : ${body.message} `;
          this.websocketData.push(result);
        });

        stompClient.subscribe(`/stock/price`, (response) => {
          console.log(response);
          let body = JSON.parse(response.body);
          let result = `${body.name} : ${body.message} `;
          this.websocketData.push(result);
        });
      });
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    },
    send() {
      let obj = { name: this.sendTo, message: this.message };


      // this.stompClient.send(`/message_to_user_test`, {}, JSON.stringify(obj));
      // this.stompClient.send(`/send_news`, {}, JSON.stringify(obj));
       this.stompClient.send(`/${  WS. sendPrefix}/message_to_user_test`, {}, JSON.stringify(obj));
      this.stompClient.send(`/${  WS. sendPrefix}/send_news`, {}, JSON.stringify(obj));
    },
  },
  created() {
    // this.init();
  },
  mounted() {
    // this.initWebSocket();
  },
  beforeDestroy: function () {
    // 页面离开时断开连接,清除定时器
    this.disconnect();
    clearInterval(this.timer);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.out_container {
  width: 100%;
  border: 1px solid red;
}
</style>
